/**
 * 广寒宫
 * 网址:www.guanghangong.xyz
 */
package com.moon.admin.framework.secure;

import java.util.ArrayList;
import java.util.List;

import com.moon.admin.framework.MoonConstants;
import com.moon.admin.framework.cache.CacheService;
import com.moon.admin.framework.config.SystemConfig;
import com.moon.admin.framework.mybatisplus.tenant.TenantDataSourceInterceptor;
import lombok.AllArgsConstructor;

import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import com.moon.admin.framework.secure.aop.AuthAspect;
import com.moon.admin.framework.secure.aop.FormRepeatSubmitAspect;
import com.moon.admin.framework.secure.aop.SecureInterceptor;
import com.moon.admin.framework.secure.props.SecureProperties;

/**
 * 安全配制
 * @author ninglong
 */
@Configuration
@EnableConfigurationProperties({SecureProperties.class})
public class SecureAutoConfiguration {
	
	@Configuration
	@AllArgsConstructor
	public class SecureConfiguration implements WebMvcConfigurer {

		private CacheService cacheService;

		private final SecureProperties secureProperties;
		private final SystemConfig systemConfig;

		@Override
		public void addInterceptors(InterceptorRegistry registry) {
			//TODO 暂时不考虑客户端验证
//			clientProperties.getClient().forEach(cs -> registry.addInterceptor(new ClientInterceptor(cs.getClientId())).addPathPatterns(cs.getPathPatterns()));
			if(secureProperties.getEnabled()==null || secureProperties.getEnabled()==false){//默认不启用
				return;
			}
			//uri 拦截
			List<String> defaultExcludePatterns = MoonConstants.STATIC_RESOUCE;
			registry.addInterceptor(new SecureInterceptor(cacheService))
					.excludePathPatterns(defaultExcludePatterns)
					.excludePathPatterns(secureProperties.getExcludePatterns());
			registry.addInterceptor(new TenantDataSourceInterceptor(systemConfig.getApplicationName()))
					.excludePathPatterns(defaultExcludePatterns)
					.excludePathPatterns(secureProperties.getExcludePatterns());
		}

		@Bean
		@ConditionalOnProperty(value = "moon.security.authEnabled",matchIfMissing=true)
		public AuthAspect authAspect() {
			return new AuthAspect();
		}
		@Bean
		@ConditionalOnProperty(value = "moon.security.formRepeatEnabled",matchIfMissing=true)
		public FormRepeatSubmitAspect formRepeatSubmitAspect() {
			return new FormRepeatSubmitAspect();
		}
	}
}